Projeto Integrador 4¶

Análise descritiva

In [53]:
import pandas as pd
import geopandas as gpd
import plotly.express as px
import matplotlib.pyplot as plt
import plotly.graph_objects as go
import tensorflow as tf
import warnings
warnings.filterwarnings('ignore')
import wordcloud
In [2]:
df=pd.read_csv("br-capes-btd-2021-2023-10-31.csv", encoding='ISO-8859-1', delimiter=';')
In [3]:
df_columns= pd.DataFrame(df.columns, columns=['Estados'])
In [4]:
df['DT_TITULACAO'].head(1)
Out[4]:
0    30JUN2021:00:00:00
Name: DT_TITULACAO, dtype: object

Trabalhos por estado¶

In [6]:
df_grouped=pd.DataFrame(df.groupby('NM_UF_IES').size())
df_grouped = df_grouped.reset_index(names='Count')
df_grouped.columns = ['Estados', 'Count']
In [7]:
fig = px.bar(df_grouped.sort_values(by='Count', ascending=False), x='Estados', y='Count', title='Distribuição de trabalhos por estado')
fig.update_layout(yaxis_title='Count', xaxis_title='Estado')
fig.show()
In [70]:
shapefile_path = "BR_UF_2022/BR_UF_2022.shp"
gdf = gpd.read_file(shapefile_path)
gdf['centroid'] = gdf.geometry.centroid

gdf.head(5)
Out[70]:
CD_UF NM_UF SIGLA_UF NM_REGIAO AREA_KM2 geometry centroid
0 12 Acre AC Norte 164173.429 POLYGON ((-68.79282 -10.99957, -68.79367 -10.9... POINT (-70.47293 -9.21327)
1 13 Amazonas AM Norte 1559255.881 POLYGON ((-56.76292 -3.23221, -56.76789 -3.242... POINT (-64.65345 -4.15411)
2 15 Pará PA Norte 1245870.704 MULTIPOLYGON (((-48.97548 -0.19834, -48.97487 ... POINT (-53.07149 -3.98042)
3 16 Amapá AP Norte 142470.762 MULTIPOLYGON (((-51.04561 -0.05088, -51.05422 ... POINT (-51.96202 1.44746)
4 17 Tocantins TO Norte 277423.627 POLYGON ((-48.2483 -13.19239, -48.24844 -13.19... POINT (-48.3313 -10.14808)
In [9]:
df_sg=pd.DataFrame(df.groupby('SG_UF_IES').size())
df_sg = df_sg.reset_index(names='Count')
df_sg.columns = ['SIGLA_UF', 'Count']
df_sg.head()
Out[9]:
SIGLA_UF Count
0 AC 215
1 AL 676
2 AM 860
3 AP 139
4 BA 3045
In [10]:
gdf_joined = gdf.merge(df_sg, how="left", on="SIGLA_UF")
gdf.head(5)
Out[10]:
CD_UF NM_UF SIGLA_UF NM_REGIAO AREA_KM2 geometry centroid
0 12 Acre AC Norte 164173.429 POLYGON ((-68.79282 -10.99957, -68.79367 -10.9... POINT (-70.47293 -9.21327)
1 13 Amazonas AM Norte 1559255.881 POLYGON ((-56.76292 -3.23221, -56.76789 -3.242... POINT (-64.65345 -4.15411)
2 15 Pará PA Norte 1245870.704 MULTIPOLYGON (((-48.97548 -0.19834, -48.97487 ... POINT (-53.07149 -3.98042)
3 16 Amapá AP Norte 142470.762 MULTIPOLYGON (((-51.04561 -0.05088, -51.05422 ... POINT (-51.96202 1.44746)
4 17 Tocantins TO Norte 277423.627 POLYGON ((-48.2483 -13.19239, -48.24844 -13.19... POINT (-48.3313 -10.14808)

Distribuição de quantidade de trabalhos por estado¶

In [11]:
fig, ax = plt.subplots(1, 1, figsize=(15, 12))
gdf_joined.plot(column="Count", cmap='OrRd', linewidth=0.8, ax=ax, edgecolor='0.8', legend=True)

for idx, row in gdf.iterrows():
    ax.text(row["centroid"].x, row["centroid"].y, row["SIGLA_UF"], fontsize=8, ha='center')

plt.show()
No description has been provided for this image
In [12]:
bar_height=20
margin_height=40
chart_height=(bar_height*len(df_grouped['Estados'])) + margin_height

df_grouped_sorted = df_grouped.sort_values(by='Count')

fig = go.Figure(go.Bar(
    x= df_grouped_sorted['Count'],
    y=df_grouped_sorted['Estados'],
    orientation='h'
))

fig.update_layout(
    title='Distribuição de trabalhos por estado',
    xaxis_title='Estado',
    yaxis_title='Número de trabalhos',
    height= chart_height,
    margin=dict(t=50,b=50)
)

fig.show()

Distribuição por área de conhecimento¶

In [13]:
df_grouped_areas_con=df.groupby('NM_GRANDE_AREA_CONHECIMENTO').size()
In [14]:
df_grouped_areas_con.head()
Out[14]:
NM_GRANDE_AREA_CONHECIMENTO
CIÊNCIAS AGRÁRIAS              7139
CIÊNCIAS BIOLÓGICAS            4335
CIÊNCIAS DA SAÚDE             12563
CIÊNCIAS EXATAS E DA TERRA     6442
CIÊNCIAS HUMANAS              14011
dtype: int64
In [15]:
df_grouped_areas_con= df_grouped_areas_con.reset_index()
df_grouped_areas_con.columns= ['Area_conhecimento', 'Count']
In [16]:
df_grouped_areas_con.head()
Out[16]:
Area_conhecimento Count
0 CIÊNCIAS AGRÁRIAS 7139
1 CIÊNCIAS BIOLÓGICAS 4335
2 CIÊNCIAS DA SAÚDE 12563
3 CIÊNCIAS EXATAS E DA TERRA 6442
4 CIÊNCIAS HUMANAS 14011
In [17]:
fig = px.bar(df_grouped_areas_con.sort_values(by='Count', ascending=False), x='Area_conhecimento', y='Count', title='Histograma Vertical')
fig.update_layout(yaxis_title='Count', xaxis_title='Area_conhecimento')
fig.show()
In [18]:
colors = px.colors.qualitative.Pastel
fig2 = go.Figure(data=[go.Pie(labels=df_grouped_areas_con['Area_conhecimento'], values=df_grouped_areas_con['Count'], hole=0.4, marker=dict(colors=colors))])
fig2.show()

Distribuição temporal¶

In [19]:
from datetime import datetime
In [20]:
df['DT_TITULACAO'] = df['DT_TITULACAO'].apply(lambda x: datetime.strptime(x,'%d%b%Y:%H:%M:%S'))
In [21]:
df['DT_TITULACAO'] = df['DT_TITULACAO'].apply(lambda x: datetime.strftime(x,'%d%m%Y'))
In [22]:
df.groupby('DT_TITULACAO')
Out[22]:
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x7fd75dded990>

Processamento de Linguagem Natural¶

In [23]:
import nltk
from nltk.tokenize import word_tokenize
from pathlib import Path

resumo_df = df[["DS_RESUMO","NM_GRANDE_AREA_CONHECIMENTO"]]
resumo_df.columns = ["resumo", "area"]
resumo_df['tokens'] = resumo_df["resumo"].apply(lambda x: word_tokenize(str(x)) if isinstance(x, str) else [])

resumo_df.head()
Out[23]:
resumo area tokens
0 O TERRITÓRIO AMAZÔNICO É RECONHECIDO PELA SUA ... MULTIDISCIPLINAR [O, TERRITÓRIO, AMAZÔNICO, É, RECONHECIDO, PEL...
1 A RELAÇÃO ENTRE O HOMEM E AS PLANTAS FOI ESTAB... MULTIDISCIPLINAR [A, RELAÇÃO, ENTRE, O, HOMEM, E, AS, PLANTAS, ...
2 A UTILIZAÇÃO DE MICRO-ORGANISMOS ENDOFÍTICOS C... MULTIDISCIPLINAR [A, UTILIZAÇÃO, DE, MICRO-ORGANISMOS, ENDOFÍTI...
3 OS FUNGOS FILAMENTOSOS SÃO CONSIDERADOS BOAS F... MULTIDISCIPLINAR [OS, FUNGOS, FILAMENTOSOS, SÃO, CONSIDERADOS, ...
4 A MALÁRIA É UMA DAS DOENÇAS MAIS FATAIS QUE AF... MULTIDISCIPLINAR [A, MALÁRIA, É, UMA, DAS, DOENÇAS, MAIS, FATAI...
In [69]:
stopwords = {word.strip() for word in set(Path("stopwords.txt").read_text().split("\n"))}
In [25]:
resumo_df["filtered"] = resumo_df["tokens"].apply(lambda x: " ".join([word for word in x if word.lower() not in stopwords]))
resumo_df.head()
Out[25]:
resumo area tokens filtered
0 O TERRITÓRIO AMAZÔNICO É RECONHECIDO PELA SUA ... MULTIDISCIPLINAR [O, TERRITÓRIO, AMAZÔNICO, É, RECONHECIDO, PEL... TERRITÓRIO AMAZÔNICO RECONHECIDO GRANDE BIODIV...
1 A RELAÇÃO ENTRE O HOMEM E AS PLANTAS FOI ESTAB... MULTIDISCIPLINAR [A, RELAÇÃO, ENTRE, O, HOMEM, E, AS, PLANTAS, ... RELAÇÃO HOMEM PLANTAS ESTABELECIDA DESDE PRIMÓ...
2 A UTILIZAÇÃO DE MICRO-ORGANISMOS ENDOFÍTICOS C... MULTIDISCIPLINAR [A, UTILIZAÇÃO, DE, MICRO-ORGANISMOS, ENDOFÍTI... UTILIZAÇÃO MICRO-ORGANISMOS ENDOFÍTICOS FONTE ...
3 OS FUNGOS FILAMENTOSOS SÃO CONSIDERADOS BOAS F... MULTIDISCIPLINAR [OS, FUNGOS, FILAMENTOSOS, SÃO, CONSIDERADOS, ... FUNGOS FILAMENTOSOS CONSIDERADOS BOAS FONTES P...
4 A MALÁRIA É UMA DAS DOENÇAS MAIS FATAIS QUE AF... MULTIDISCIPLINAR [A, MALÁRIA, É, UMA, DAS, DOENÇAS, MAIS, FATAI... MALÁRIA DOENÇAS FATAIS AFETA HUMANIDADE . DURA...
In [26]:
resumo_df['area'].unique()
Out[26]:
array(['MULTIDISCIPLINAR', 'CIÊNCIAS BIOLÓGICAS', 'CIÊNCIAS DA SAÚDE',
       'ENGENHARIAS', 'CIÊNCIAS AGRÁRIAS', 'LINGÜÍSTICA, LETRAS E ARTES',
       'CIÊNCIAS SOCIAIS APLICADAS', 'CIÊNCIAS HUMANAS',
       'CIÊNCIAS EXATAS E DA TERRA'], dtype=object)
In [55]:
output = Path("results")
output.mkdir(parents=True, exist_ok=True)

list_words=[]

grouped_area = resumo_df.groupby("area")["filtered"].apply(' '.join).reset_index()

for index, row in grouped_area.iterrows():

    filename = output / f"{row['area']}.png"

    word = wordcloud.WordCloud(width=800, height=400, background_color="white", stopwords=stopwords).generate(row['filtered'])

    list_words.append(word)
    
In [59]:
plt.figure(figsize=(10, 5))
plt.imshow(list_words[0], interpolation="bilinear")
plt.axis('off')  # Turn off axis
plt.show()
No description has been provided for this image
In [60]:
plt.figure(figsize=(10, 5))
plt.imshow(list_words[1], interpolation="bilinear")
plt.axis('off')  # Turn off axis
plt.show()
No description has been provided for this image
In [61]:
plt.figure(figsize=(10, 5))
plt.imshow(list_words[2], interpolation="bilinear")
plt.axis('off')  # Turn off axis
plt.show()
No description has been provided for this image
In [62]:
plt.figure(figsize=(10, 5))
plt.imshow(list_words[3], interpolation="bilinear")
plt.axis('off')  # Turn off axis
plt.show()
No description has been provided for this image
In [63]:
plt.figure(figsize=(10, 5))
plt.imshow(list_words[4], interpolation="bilinear")
plt.axis('off')  # Turn off axis
plt.show()
No description has been provided for this image
In [64]:
plt.figure(figsize=(10, 5))
plt.imshow(list_words[5], interpolation="bilinear")
plt.axis('off')  # Turn off axis
plt.show()
No description has been provided for this image
In [65]:
plt.figure(figsize=(10, 5))
plt.imshow(list_words[6], interpolation="bilinear")
plt.axis('off')  # Turn off axis
plt.show()
No description has been provided for this image
In [66]:
plt.figure(figsize=(10, 5))
plt.imshow(list_words[7], interpolation="bilinear")
plt.axis('off')  # Turn off axis
plt.show()
No description has been provided for this image
In [67]:
plt.figure(figsize=(10, 5))
plt.imshow(list_words[8], interpolation="bilinear")
plt.axis('off')  # Turn off axis
plt.show()
No description has been provided for this image